<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>{{ isLogin ? '登录' : '注册' }}</span>
        </div>
      </template>
      
      <el-form :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">{{ isLogin ? '登录' : '注册' }}</el-button>
          <el-button @click="toggleMode">切换到{{ isLogin ? '注册' : '登录' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'LoginView',
  setup() {
    const store = useStore()
    const router = useRouter()
    const isLogin = ref(true)
    const form = ref({
      username: '',
      password: ''
    })

    const handleSubmit = async () => {
      if (!form.value.username || !form.value.password) {
        ElMessage.warning('请填写完整信息')
        return
      }

      try {
        if (isLogin.value) {
          await store.dispatch('login', form.value)
          ElMessage.success('登录成功')
          router.push('/todos')
        } else {
          console.log('Registering with:', form.value)
          await store.dispatch('register', form.value)
          ElMessage.success('注册成功')
          isLogin.value = true
          form.value = {
            username: '',
            password: ''
          }
        }
      } catch (error) {
        console.error('Operation failed:', error)
        ElMessage.error(error.message || '操作失败')
      }
    }

    const toggleMode = () => {
      isLogin.value = !isLogin.value
      form.value = {
        username: '',
        password: ''
      }
    }

    return {
      isLogin,
      form,
      handleSubmit,
      toggleMode
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
}

.card-header {
  text-align: center;
  font-size: 20px;
}
</style> 